import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_library_index_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_wait_play_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_library_index_grid_page.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../media_library_index_played_view_model.dart';
import '../media_library_index_playing_view_model.dart';
import 'media_library_play_page.dart';

/// 批量删除资料库
class HandleMediaLibraryPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "HandleMediaLibraryPage";
  final String pageType;

  const HandleMediaLibraryPage({Key key, this.pageType})
      : super(key: key);

  @override
  HandleMediaLibraryPageState createState() => HandleMediaLibraryPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String pageType) {
    return RouterUtils.routeForFutureResult(
      context,
      HandleMediaLibraryPage(pageType: pageType,),
      routeName: HandleMediaLibraryPage.ROUTER,
    );
  }
}

class HandleMediaLibraryPageState
    extends BasePagerState<MediaLibraryIndexListItemBean, HandleMediaLibraryPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {
  MediaLibraryIndexViewModel _deleteViewModel;
  BasePagerViewModel _viewModel;

  StreamSubscription _streamSubscription;
  StreamSubscription _mediaLibraryStreamSubscription;
  StreamSubscription _terminalNumRefreshSubscription;
  ///获取state
  static HandleMediaLibraryPageState of(BuildContext context) {
    final HandleMediaLibraryPageState result =
    context.findAncestorStateOfType<HandleMediaLibraryPageState>();
    return result;
  }

  List<String> _toDeleteList;

  bool isAliveConfirm = false;

  @override
  void initState() {
    super.initState();
    _toDeleteList = new List();
    _deleteViewModel = MediaLibraryIndexViewModel(this);
    if(MediaLibraryPlayPage.TYPE_PLAYED == widget?.pageType){
      _viewModel = MediaLibraryIndexPlayedViewModel(this);
    }else if(MediaLibraryPlayPage.TYPE_PLAYING == widget?.pageType){
      _viewModel = MediaLibraryIndexPlayingViewModel(this);
    }else if(MediaLibraryPlayPage.TYPE_WAIT_PLAY == widget?.pageType){
      _viewModel = MediaLibraryIndexWaitPlayViewModel(this);
    }
    _viewModel?.refresh();
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    _streamSubscription?.cancel();
    _mediaLibraryStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainColumnWidget(),
    );
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: _toMainPlaceHolderWidget(),
        )
      ],
    );
  }

  Widget _toTopBarWidget() {
    final double statusHeight = ScreenUtils.getStatusBarH(context);
    return Container(
      height: 44 + statusHeight,
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      padding: EdgeInsets.only(top: statusHeight),
      child: Row(
        children: <Widget>[
          SizedBox(
            width: 15,
          ),
          Text(
            _toDeleteList.length>0?"已选择${_toDeleteList.length}":"请选择",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 17,
                height: 1.22,
                fontWeight: FontWeight.w600),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              RouterUtils.pop(context);
            },
            child: Container(
              padding: const EdgeInsets.only(left: 10,right: 10),
              height: 23,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Color(0xFF424957),
                  borderRadius: BorderRadius.all(Radius.circular(12))),
              child: Text(
                "取消",
                style: TextStyle(
                  fontSize: 12,
                  height: 1.2,
                  color: Colors.white
                ),
              ),
            ),
          ),
          SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  Widget _toMainPlaceHolderWidget() {
    return _toFilterAndListWidget();
  }

  Widget _toFilterAndListWidget() {
    return Column(
      children: <Widget>[
        SizedBox(height: 15,),
        Expanded(
          child: ScrollConfiguration(
            behavior: MyBehavior(),
            child: _toPlaceHolderWidget(
                child: MediaLibraryIndexGridPage(
                  list: data,
                  onTap: _onTap,
                  canSelect: true,
                  pageType: widget?.pageType,
                ))
          ),
        ),
        _toBottomWidget(),
      ],
    );
  }

  Widget _toBottomWidget(){
    final double bottomH = ScreenUtils.getBottomBarH(context);
    return Container(
      margin: EdgeInsets.only(bottom: bottomH),
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isAliveConfirm,
        height: 49,
        radius: BorderRadius.all(Radius.circular(0)),
        width: ScreenUtils.screenW(context),
        margin: const EdgeInsets.symmetric(horizontal: 0),
        unSelectBgColor: Color(0xFF3A3F50),
        selectedBgColor:
        ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 17,
        ),
        selectedTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 17,
        ),
        text: "删除文件",
        onTap: ()async{
          if(_toDeleteList != null && _toDeleteList.length > 0){
            String ids = "";
            bool playFlag = false;
            _toDeleteList.forEach((element) {
              ids += element;
              ids += ",";
            });
            data.forEach((element) {
              if(element?.attnum != null && element.attnum > 0 && _toDeleteList.contains(element.id)){
                playFlag = true;
              }
            });
            String content = "选中文件删除后无法找回，确认继续？";
            if(playFlag){
              content = "选中文件正在播放中，确认继续删除？";
            }
            bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: content,
                cancelText: "取消",
                confirmText: "删除",
                confirmBgColor: ThemeRepository.getInstance()
                    .getMinorRedColor_F95355());
            if (result ?? false) {
              if(StringUtils.isNotEmpty(ids)){
                ids = ids.substring(0, ids.length-1);
              }
              _deleteViewModel.deletePics(context, ids);
            }

          }
        },
      ),
    );
  }

  Widget _toPlaceHolderWidget({Widget child}) {
    return VgPlaceHolderStatusWidget(
        emptyStatus: data == null || data.isEmpty,
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        loadingStatus: data == null,
        child: VgPullRefreshWidget.bind(
            state: this, viewModel: _viewModel, child: child));
  }

  void _onTap(MediaLibraryIndexListItemBean itemBean) {
    if (itemBean == null) {
      return null;
    }
    _handleSelectedStatus(itemBean);
  }

  ///处理选中状态
  void _handleSelectedStatus(MediaLibraryIndexListItemBean itemBean) {
    if (itemBean == null || StringUtils.isEmpty(itemBean.id)) {
      VgToastUtils.toast(context, "错误资源");
      return;
    }
    if (itemBean?.selectStatus??false) {
      _removeLabel(itemBean.id);
    } else {
      _addLabel(itemBean.id);
    }
  }

  void _addLabel(String selectedId) {
    _toDeleteList?.add(selectedId);
    _handleUpdateList(data);
  }

  void _removeLabel(String removeId) {
    _toDeleteList?.remove(removeId);
    _handleUpdateList(data);
  }

  void _handleUpdateList(List<MediaLibraryIndexListItemBean> list) {
    if (list == null || list.isEmpty) {
      return;
    }
    list?.removeWhere((element) => StringUtils.isEmpty(element?.id));
    for (MediaLibraryIndexListItemBean item in list) {
      if(_toDeleteList.contains(item.id)){
        item.selectStatus = true;
      }else{
        item.selectStatus = false;
      }
    }

    isAliveConfirm = _toDeleteList.length>0;

    print("打印结果"
        "\n"
        "${_toDeleteList.toString()}");
    setState(() {});
  }



  @override
  bool get wantKeepAlive => true;
}
